#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
带智能纠错的SQL编译器
集成了智能错误检测和修复建议的完整SQL编译系统

实现功能：
1. 完整的SQL编译流程（词法分析->语法分析->语义分析->代码生成）
2. 智能错误检测和纠错建议
3. 用户友好的错误报告和修复建议
4. 交互式和批量编译模式
"""

from typing import List, Dict, Set, Optional
import sys
import os
from LexicalAnalysis import LexicalAnalyzer
from SyntaxAnalysis import SyntaxAnalyzer
from SemanticAnalysis import SemanticAnalyzer
from CodeGeneration import CodeGenerator, run_compilation_with_error_correction


class SmartSqlCompiler:
    """带智能纠错的SQL编译器"""
    
    def __init__(self):
        # 创建各个分析器实例
        self.lexical_analyzer = LexicalAnalyzer()
        self.syntax_analyzer = SyntaxAnalyzer()
        self.semantic_analyzer = SemanticAnalyzer()
        self.code_generator = CodeGenerator()
        
        # 编译统计
        self.total_compiled = 0
        self.successful_compilations = 0
        self.failed_compilations = 0
        
        # 是否是第一次运行（用于构建语法分析表）
        self.is_first_run = True
    
    def compile_sql(self, sql_statement: str, show_process: bool = False) -> Dict:
        """
        编译单个SQL语句
        
        Args:
            sql_statement: SQL语句
            show_process: 是否显示编译过程
            
        Returns:
            编译结果字典，包含编译状态和纠错信息
        """
        self.total_compiled += 1
        
        # 确定输出模式
        output_modes = {0}  # 默认只显示结果
        if show_process:
            output_modes = {1, 2, 3, 4}  # 显示所有过程
        
        print(f"\n🔍 正在编译SQL语句: {sql_statement}")
        print("-" * 60)
        
        # 运行编译
        results = run_compilation_with_error_correction(
            sql_statement, output_modes, self.lexical_analyzer, 
            self.syntax_analyzer, self.semantic_analyzer, 
            self.code_generator, self.is_first_run, show_corrections=True  # 收集纠错信息
        )
        
        self.is_first_run = False  # 后续编译不再是第一次
        
        # 显示编译结果
        print(f"\n编译结果:")
        if results['lexical']:
            print("  ✅ 词法分析：通过")
        else:
            print("  ❌ 词法分析：失败")
            
        if results['syntax']:
            print("  ✅ 语法分析：通过")
        else:
            print("  ❌ 语法分析：失败")
            
        if results['semantic']:
            print("  ✅ 语义分析：通过")
        else:
            print("  ❌ 语义分析：失败")
            
        if results['code_gen']:
            print("  ✅ 目标代码生成：通过")
        else:
            print("  ❌ 目标代码生成：失败")
        
        # 在编译结果之后显示智能纠错报告
        any_corrections = any(results['corrections'][stage].strip() for stage in results['corrections'])
        if any_corrections:
            print(f"\n🔍 智能纠错报告")
            print("=" * 50)
            
            # 检查是否有错误发生
            has_errors = False
            error_messages = []
            for stage_name, stage_key in [("词法分析", "lexical"), ("语法分析", "syntax"), ("语义分析", "semantic")]:
                if results['corrections'][stage_key].strip():
                    has_errors = True
                    # 提取关键错误信息，避免显示冗余内容
                    error_content = results['corrections'][stage_key]
                    lines = error_content.split('\n')
                    for line in lines:
                        if line.strip() and ('错误' in line or 'ERROR' in line or '第' in line):
                            if '智能纠错报告' not in line and '智能修复建议' not in line:
                                error_messages.append(f"[{stage_name}] {line.strip()}")
            
            if has_errors and error_messages:
                print(f"\n❌ 发现的问题:")
                for msg in error_messages[:3]:  # 只显示前3个最重要的错误
                    print(f"  {msg}")
                
        
        # 统计结果
        if self._is_compilation_successful(results):
            self.successful_compilations += 1
        else:
            self.failed_compilations += 1
            
            # 显示失败阶段
            failed_stages = []
            if not results['lexical']:
                failed_stages.append("词法分析")
            if not results['syntax']:
                failed_stages.append("语法分析")
            if not results['semantic']:
                failed_stages.append("语义分析")
            if not results['code_gen']:
                failed_stages.append("代码生成")
        
        return results
    
    def _is_compilation_successful(self, results: Dict) -> bool:
        """检查编译是否成功"""
        return all([
            results['lexical'],
            results['syntax'],
            results['semantic'],
            results['code_gen']
        ])
    
    def batch_compile(self, sql_statements: List[str], show_process: bool = False) -> List[Dict]:
        """
        批量编译SQL语句
        
        Args:
            sql_statements: SQL语句列表
            show_process: 是否显示编译过程
            
        Returns:
            编译结果列表
        """
        print(f"\n🚀 开始批量编译 {len(sql_statements)} 个SQL语句")
        print("=" * 80)
        
        results = []
        for i, sql in enumerate(sql_statements, 1):
            print(f"\n📋 编译任务 {i}/{len(sql_statements)}")
            result = self.compile_sql(sql, show_process)
            results.append(result)
        
        # 显示批量编译总结
        self._print_batch_summary()
        
        return results
    
    def _print_batch_summary(self):
        """打印批量编译总结"""
        print(f"\n{'='*80}")
        print("📊 批量编译总结")
        print(f"{'='*80}")
        print(f"总编译数: {self.total_compiled}")
        print(f"成功编译: {self.successful_compilations}")
        print(f"失败编译: {self.failed_compilations}")
        
        if self.total_compiled > 0:
            success_rate = (self.successful_compilations / self.total_compiled) * 100
            print(f"成功率: {success_rate:.1f}%")
        
        print(f"{'='*80}")
    
    def interactive_mode(self):
        """交互式编译模式"""
        print("🎯 智能SQL编译器 - 交互模式")
        print("输入SQL语句进行编译，系统将提供智能纠错建议")
        print("命令:")
        print("  - 输入SQL语句: 直接编译")
        print("  - 'process': 切换是否显示编译过程")
        print("  - 'stats': 显示编译统计")
        print("  - 'reset': 重置统计")
        print("  - 'help': 显示帮助")
        print("  - 'quit' 或 'exit': 退出")
        print("-" * 60)
        
        show_process = False
        
        while True:
            try:
                user_input = input("\nSQL> ").strip()
                
                if not user_input:
                    continue
                
                # 处理命令
                if user_input.lower() in ['quit', 'exit']:
                    print("👋 感谢使用智能SQL编译器！")
                    break
                elif user_input.lower() == 'help':
                    self._show_help()
                elif user_input.lower() == 'process':
                    show_process = not show_process
                    status = "开启" if show_process else "关闭"
                    print(f"📋 编译过程显示已{status}")
                elif user_input.lower() == 'stats':
                    self._print_batch_summary()
                elif user_input.lower() == 'reset':
                    self._reset_stats()
                    print("📊 统计信息已重置")
                else:
                    # 编译SQL语句
                    self.compile_sql(user_input, show_process)
                    
            except KeyboardInterrupt:
                print("\n\n👋 感谢使用智能SQL编译器！")
                break
            except Exception as e:
                print(f"\n❌ 系统错误: {e}")
    
    def _show_help(self):
        """显示帮助信息"""
        print("\n📖 智能SQL编译器帮助")
        print("-" * 40)
        print("支持的SQL语句类型:")
        print("  • SELECT语句: SELECT column FROM table WHERE condition")
        print("  • CREATE语句: CREATE TABLE/DATABASE/USER")
        print("  • INSERT语句: INSERT INTO table VALUES (...)")
        print("  • UPDATE语句: UPDATE table SET column=value WHERE condition")
        print("  • DELETE语句: DELETE FROM table WHERE condition")
        print("  • DROP语句: DROP TABLE/DATABASE/USER")
        print("  • USE语句: USE database")
        print("  • GRANT语句: GRANT privileges ON object TO user")
        print("  • LIST/SHOW语句: LIST/SHOW DATABASES/USERS")
        print("\n智能纠错功能:")
        print("  • 拼写错误检测和修复建议")
        print("  • 语法错误定位和修复提示")
        print("  • 语义错误分析和相似名称推荐")
        print("  • 多种置信度的修复建议")
        print("-" * 40)
    
    def _reset_stats(self):
        """重置统计信息"""
        self.total_compiled = 0
        self.successful_compilations = 0
        self.failed_compilations = 0


def main():
    """主函数"""
    compiler = SmartSqlCompiler()
    
    # 检查命令行参数
    if len(sys.argv) > 1:
        # 批量模式：从命令行参数或文件读取SQL语句
        if sys.argv[1] == '--file' and len(sys.argv) > 2:
            # 从文件读取SQL语句
            filename = sys.argv[2]
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    sql_statements = [line.strip() for line in f.readlines() if line.strip()]
                
                show_process = '--verbose' in sys.argv
                compiler.batch_compile(sql_statements, show_process)
                
            except FileNotFoundError:
                print(f"❌ 文件未找到: {filename}")
            except Exception as e:
                print(f"❌ 读取文件错误: {e}")
        
        elif sys.argv[1] == '--demo':
            # 演示模式：运行预定义的测试用例
            demo_sql_statements = [
                # 正确的SQL语句
                "SELECT name FROM Students;",
                "CREATE USER test_user;",
                "USE test_db;",
                
                # 有错误的SQL语句（用于展示纠错功能）
                "SELCT name FORM Students;",  # 拼写错误
                "SELECT FROM Students;",       # 语法错误
                "SELECT name FROM UnknownTable;",  # 语义错误
                "SELECT name FROM Students",   # 缺少分号
                "DELETE FROM Students;",       # 缺少WHERE子句
            ]
            
            show_process = '--verbose' in sys.argv
            print("🎪 智能SQL编译器演示模式")
            compiler.batch_compile(demo_sql_statements, show_process)
        
        else:
            # 单个SQL语句编译
            sql = ' '.join(sys.argv[1:])
            show_process = '--verbose' in sys.argv
            compiler.compile_sql(sql, show_process)
    
    else:
        # 交互模式
        compiler.interactive_mode()


if __name__ == "__main__":
    main()
